<script setup lang="ts">
import { useConfigTableStore } from '@/stores/config/configTableStore';
import { computed, ref, watch } from 'vue';
import { ViewHelper } from '@/utils/viewHelper';

const props = defineProps({
    modelValue: Boolean,
    tableId: {
        type: Number,
        required: true
    }
});

const emit = defineEmits(['update:modelValue', 'confirm']);

const tableStore = useConfigTableStore();
const selectedRowId = ref(0);

const currentTable = computed(() => tableStore.getTable(props.tableId));

const handleRowClick = (row: any) => {
    selectedRowId.value = row?.id || 0;
};

const onConfirm = () => {
    if (selectedRowId.value) {
        emit('confirm', selectedRowId.value);
    }
    emit('update:modelValue', false);
};

watch(() => props.modelValue, (newVal) => {
    if (!newVal) {
        selectedRowId.value = 0;
    }
});
</script>

<template>
    <el-dialog
        :model-value="modelValue"
        @update:modelValue="(val: any) => emit('update:modelValue', val)"
        title="选择表格行"
        width="70%">
        <div v-if="!currentTable" class="error-message">
            表格不存在（ID：{{ tableId }}）
        </div>
        <el-table
            v-else
            :data="currentTable.rows"
            highlight-current-row
            @current-change="handleRowClick">
            <el-table-column label="行ID" prop="id" width="100" />
            <el-table-column 
                v-for="(header, index) in currentTable.tableHeader"
                :key="index"
                :label="header.label">
                <template #default="{ row }">
                    {{ ViewHelper.getTableElementText(header, row.values[index]) }}
                </template>
            </el-table-column>
        </el-table>
        <template #footer>
            <el-button @click="emit('update:modelValue', false)">取消</el-button>
            <el-button type="primary" @click="onConfirm">确定</el-button>
        </template>
    </el-dialog>
</template>

<style scoped>
.error-message {
    color: #F56C6C;
    padding: 20px;
    text-align: center;
}
.el-table {
    margin: 15px 0;
}
</style>